// createRouter;用于创建路由
// createWebHistory;用于设置路由模式为哈希模式
import { createRouter, createWebHistory } from 'vue-router'
import store from '@/store/index.js'
import nprogress from 'nprogress'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/home',
      component: ()=>import('@/components/Home.vue')
    },
    // 捕获404路由
    {
        path:'/:pathMatch(.*)*',
        name:'NotFound',
        component:()=>import('@/views/404.vue')
    },
    {
      path:'/login',
      component:()=>import('@/views/login.vue')
    }
  ]
})

// 全局前置路由守卫
router.beforeEach(async(to, from, next) => {
  nprogress.start()
  // 获取token
  const tokenStr=window.sessionStorage.getItem('token')
  if(tokenStr){
     await store.dispatch('getUser')
  }
  // 如果未登录，则跳转到登录页面
  if(!tokenStr&& to.path!=='/login'){
     return next('/login')   
  }
// 如果已登录，则禁止返回登录页面
  if(tokenStr&& to.path=='/login'){
    return next({path:from.path?from.path:'/'})   
 }
 next()
})

// 全局后置路由守卫
router.afterEach((to,form)=>{
  nprogress.done()
})

export default router
